package com.java110.mall.shop.cmd.shopVisit;

import com.alibaba.fastjson.JSONObject;
import com.java110.core.annotation.Java110Cmd;
import com.java110.core.context.ICmdDataFlowContext;
import com.java110.core.event.cmd.Cmd;
import com.java110.core.event.cmd.CmdEvent;
import com.java110.dto.shop.ShopVisitDto;
import com.java110.intf.shop.IShopVisitInnerServiceSMO;
import com.java110.utils.exception.CmdException;
import com.java110.utils.util.Assert;
import com.java110.utils.util.BeanConvertUtil;
import com.java110.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import java.util.ArrayList;
import java.util.List;

/**
 * 查询店铺访问记录
 */
@Java110Cmd(serviceCode = "shopVisit.queryShopVisit")
public class QueryShopVisitCmd extends Cmd {

    @Autowired
    private IShopVisitInnerServiceSMO shopVisitInnerServiceSMOImpl;

    @Override
    public void validate(CmdEvent event, ICmdDataFlowContext context, JSONObject reqJson) throws CmdException {
        super.validatePageInfo(reqJson);
        Assert.hasKeyAndValue(reqJson, "shopId", "未包含商铺");
    }

    @Override
    public void doCmd(CmdEvent event, ICmdDataFlowContext context, JSONObject reqJson) throws CmdException {
        ShopVisitDto shopVisitDto = BeanConvertUtil.covertBean(reqJson, ShopVisitDto.class);
        int count = shopVisitInnerServiceSMOImpl.queryShopVisitsCount(shopVisitDto);

        List<ShopVisitDto> shopVisitDtos = null;
        if (count > 0) {
            shopVisitDtos = shopVisitInnerServiceSMOImpl.queryShopVisits(shopVisitDto);
            codeUserName(shopVisitDtos);
        } else {
            shopVisitDtos = new ArrayList<>();
        }

        ResultVo resultVo = new ResultVo((int) Math.ceil((double) count / (double) shopVisitDto.getRow()), count, shopVisitDtos);

        ResponseEntity<String> responseEntity = new ResponseEntity<String>(resultVo.toString(), HttpStatus.OK);
        context.setResponseEntity(responseEntity);
    }


    private void codeUserName(List<ShopVisitDto> shopVisitDtos) {
        for (ShopVisitDto shopVisitDto : shopVisitDtos) {
            shopVisitDto.setVisitUserName("**" + shopVisitDto.getVisitUserName().substring(shopVisitDto.getVisitUserName().length() - 1));
        }
    }
}
